//
//  QianliAppearProgressView.swift
//  todoios
//
//  Created by 子凡 on 2025/7/31.
//

import Foundation
import UIKit


class QianliAppearProgressView: UIView, CAAnimationDelegate {
    
    var completeBlock: ((Bool) -> Void)?
    var readyBlock: ((Bool) -> Void)?
    
    private var DreGDeCQ84e4nc1x: Bool = false
    private var w5CfLoFfug16xO3a: Bool = false
    private var G2DzSQUmmgBLo4Ay: Bool = true
    
    private var YwDMX5reuL8EOlPi: QianliAppearProgressIndicator!
    private var KY8FqIoEWu8BspOB: Bool = false
    private var kwMDFSOrxdZjDAWK: Bool = false
    private var ZpbzoxFHxLB5mXgS: CGFloat = 0.0
    
    // 常量定义
    private let ZBvVjUVz8p7Gv9Jy = "kIndicatorToStartAnimationKey"
    private let MUBVr9vIKhBFT9am = "kreadyForAppearLoadingAnimationKey"

    private let Irc1Jg46EECfIgj8: CGFloat = .pi / 12  // M_PI_4/3
    private let EuUWXFBxK6WD8dcH: CGFloat = .pi / 16   // M_PI_4/4
    private let s4r95rIqDiUNJQYY: CGFloat = 4.0

    private lazy var containerLayer: CAShapeLayer = {
        let layer = DNfsqbWS4ApUmVLe()
        let rect = CGRect(
            x: (bounds.width - bounds.height) / 2,
            y: 0,
            width: bounds.height,
            height: bounds.height
        )
        layer.path = UIBezierPath(roundedRect: rect, cornerRadius: 5).cgPath
        return layer
    }()
    
    private lazy var progressLayer: CAShapeLayer = {
        let layer = DNfsqbWS4ApUmVLe()
        layer.lineWidth = self.s4r95rIqDiUNJQYY
        layer.fillColor = UIColor.init(51, 102, 255).cgColor
        layer.strokeColor = UIColor.init(51, 102, 255).cgColor
        return layer
    }()
    
    private func DNfsqbWS4ApUmVLe() -> CAShapeLayer {
        let layer = CAShapeLayer()
        layer.fillColor = UIColor.systemGray.cgColor
        layer.strokeColor = UIColor.clear.cgColor
        layer.lineCap = .round
        layer.lineJoin = .round
        layer.frame = bounds
        return layer
    }
    
    private var _displayLink: CADisplayLink?
    
    private var W2ibSoTH4X899TM3: CADisplayLink? {
        get {
            if _displayLink == nil {
                let link = CADisplayLink(target: self, selector: #selector(DByenIGqOb35guUv))
                // 优先使用高帧率模式（iOS 15+支持）
                if #available(iOS 15.0, *) {
                    link.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 60, preferred: 60)
                }
                _displayLink = link
            }
            return _displayLink
        }
        set {
            _displayLink = newValue
        }
    }
    
    
    // 析构方法
    deinit {
        print("QianliAppearProgressView.deinit")
    }
    
    
    var progress: CGFloat = 0.0 {
        didSet {
            let clampedProgress = min(max(progress, 0.0), 1.0)
            if progress != clampedProgress {
                progress = clampedProgress
                return
            }
            
//            if !isAnimating && !isSuccess {
                DispatchQueue.main.async {
                    self.YwDMX5reuL8EOlPi.progress = clampedProgress
                }
//            }
            
            if progress == 1.0 && self.kwMDFSOrxdZjDAWK {
                // 防止最后一次刷新无法进行
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    self.W2ibSoTH4X899TM3?.remove(from: .current, forMode: .default)
                }
                self.kwMDFSOrxdZjDAWK = false
                self.DreGDeCQ84e4nc1x = true
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        z5FoekEhx4Vm1Joo()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        z5FoekEhx4Vm1Joo()
    }
    
    private func z5FoekEhx4Vm1Joo() {
        self.kwMDFSOrxdZjDAWK = false
        self.DreGDeCQ84e4nc1x = false
        self.KY8FqIoEWu8BspOB = false
        self.w5CfLoFfug16xO3a = false
        self.G2DzSQUmmgBLo4Ay = true
        self.ZpbzoxFHxLB5mXgS = 0.0
        
        // 初始化图层
        layer.addSublayer(containerLayer)
        layer.addSublayer(progressLayer)
        
        // 初始化指示器
        let indicatorFrame = CGRect(
            x: (bounds.width - bounds.height) / 2,
            y: 0,
            width: bounds.height,
            height: bounds.height
        )
        self.YwDMX5reuL8EOlPi = QianliAppearProgressIndicator(frame: indicatorFrame)
        self.YwDMX5reuL8EOlPi.completeBlock = { [weak self] flag in
            guard let self = self else { return }
            self.w5CfLoFfug16xO3a = false
            self.completeBlock?(flag)
        }
        addSubview(self.YwDMX5reuL8EOlPi)
    }
    
    func S9RnAOPK9bshC6dc() {
        if !self.G2DzSQUmmgBLo4Ay {
            return
        }
        self.KY8FqIoEWu8BspOB = true
        self.w5CfLoFfug16xO3a = true
        self.G2DzSQUmmgBLo4Ay = false
        self.YwDMX5reuL8EOlPi.Fu54WsDms21twvGP()
        Fu54WsDms21twvGP()
    }
    
    func gkP1dBZNr89L0fsw() {
        if self.G2DzSQUmmgBLo4Ay {
            return
        }
        self.FUvx9Y9awNBL4cs3()
    }
    
    private func nZTzCCM9d37yx7nx() {
        // 容器层动画
        let transformAnim = CABasicAnimation(keyPath: "transform")
        transformAnim.toValue = NSValue(caTransform3D: CATransform3DIdentity)
        transformAnim.fillMode = .forwards
        transformAnim.isRemovedOnCompletion = false
        transformAnim.duration = 0.3
        containerLayer.add(transformAnim, forKey: "ContainerOriginAnimationKey")
        
        // 指示器移动路径
        let pathPoint = self.Stl4QlFQ7v5yoQ33().currentPoint
        let startPoint = CGPoint(x: bounds.width * progress, y: pathPoint.y)
        let ctrlPoint = CGPoint(x: bounds.width / 2, y: bounds.height / 2 - 100)
        let endPoint = self.YwDMX5reuL8EOlPi.center
        
        let movePath = UIBezierPath()
        movePath.move(to: startPoint)
        movePath.addQuadCurve(to: endPoint, controlPoint: ctrlPoint)
        
        // 指示器移动动画
        let moveAnim = CAKeyframeAnimation(keyPath: "position")
        moveAnim.path = movePath.cgPath
        moveAnim.duration = 0.3
        moveAnim.fillMode = .forwards
        moveAnim.isRemovedOnCompletion = false
        self.YwDMX5reuL8EOlPi.layer.add(moveAnim, forKey: "resumeAnimaitonKey")
        
        // 进度条透明度动画
        let opacityAnim = CABasicAnimation(keyPath: "opacity")
        opacityAnim.fillMode = .forwards
        opacityAnim.isRemovedOnCompletion = false
        opacityAnim.toValue = 0
        opacityAnim.duration = 0.05
        progressLayer.add(opacityAnim, forKey: "progressHiddenAnim")
    }
    
    private func FUvx9Y9awNBL4cs3() {
        self.KY8FqIoEWu8BspOB = true
        let duration = 0.5 * progress
        
        // 进度条消失动画
        let dismissAnim = self.v5bH1SlyYCbABaky()
        dismissAnim.duration = duration
        progressLayer.add(dismissAnim, forKey: "progressDissmissAnimationKey")
        
        // 创建失败线条图层
        let downLayer = CALayer()
        downLayer.anchorPoint = CGPoint(x: 0, y: 0)
        downLayer.frame = CGRect(x: bounds.width * progress, y: bounds.height / 2, width: 2, height: 0)
        downLayer.backgroundColor = UIColor.label.cgColor
        downLayer.cornerRadius = 2.5
        layer.addSublayer(downLayer)
        
        // 失败线条动画
        let downAnim = self.j5foJnq7d5H6ddLX()
        downAnim.duration = duration
        downLayer.add(downAnim, forKey: "progressDownAnimationKey")
        
        // 下落动画
        let fallAnim = self.rzCSMmrGMQ2fK2Bu()
        fallAnim.duration = 0.7
        fallAnim.beginTime = CACurrentMediaTime() + duration
        downLayer.add(fallAnim, forKey: "progressFallAnimationKey")
        
        // 指示器显示失败状态
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.4) {
            self.YwDMX5reuL8EOlPi.handleAppearLoadingFailed()
            downLayer.removeFromSuperlayer()
        }
        
        // 失败动画完成后允许resume响应
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.7) {
            self.KY8FqIoEWu8BspOB = false
        }
    }
    
    private func Fu54WsDms21twvGP() {
        let xScale = bounds.width / bounds.height
        let yScale = self.s4r95rIqDiUNJQYY / bounds.height
        
        // 容器层变形动画
        let transformAnim = CABasicAnimation(keyPath: "transform")
        transformAnim.toValue = NSValue(caTransform3D: CATransform3DMakeScale(xScale, yScale, 1))
        transformAnim.duration = 0.3
        transformAnim.fillMode = .forwards
        transformAnim.isRemovedOnCompletion = false
        containerLayer.add(transformAnim, forKey: "kContainerReadyAnimationKey")
        
        // 指示器准备动画
        let indicatorAnim = self.N5sy4OSW2ysIM73z()
        indicatorAnim.delegate = self
        self.YwDMX5reuL8EOlPi.layer.add(indicatorAnim, forKey: self.ZBvVjUVz8p7Gv9Jy)
    }
    
    private func VSlnkd8KRp2HhFsy() {
        // 指示器旋转动画
        let rotationAnim = CAKeyframeAnimation(keyPath: "transform.rotation.z")
        rotationAnim.values = [-self.EuUWXFBxK6WD8dcH, 0]
        rotationAnim.keyTimes = [0.5, 1.0]
        rotationAnim.duration = 0.2
        rotationAnim.fillMode = .forwards
        rotationAnim.isRemovedOnCompletion = false
        rotationAnim.delegate = self
        self.YwDMX5reuL8EOlPi.layer.add(rotationAnim, forKey: self.MUBVr9vIKhBFT9am)
    }
    
    @objc private func DByenIGqOb35guUv() {
        // 更新指示器位置和进度条路径
//        self.YwDMX5reuL8EOlPi.transform = CGAffineTransform(translationX: bounds.width * progress, y: 0)
//        progressLayer.path = lagrRo1SCer3ifmP(with: progress).cgPath
        
        let targetX = bounds.width * progress
        CATransaction.begin()
        CATransaction.setDisableActions(true) //关闭隐式动画
        self.YwDMX5reuL8EOlPi.transform = CGAffineTransform(translationX: targetX, y: 0)
        progressLayer.path = self.lagrRo1SCer3ifmP(with: progress).cgPath
        CATransaction.commit()
    
    }

    private func N5sy4OSW2ysIM73z() -> CAAnimationGroup {
        // 移动动画
        let moveAnim = CAKeyframeAnimation(keyPath: "position")
        moveAnim.path = self.Stl4QlFQ7v5yoQ33().cgPath
        
        // 旋转动画
        let rotationAnim = CAKeyframeAnimation(keyPath: "transform.rotation.z")
        rotationAnim.values = [0, self.Irc1Jg46EECfIgj8]
        rotationAnim.keyTimes = [0.4, 0.7]
        
        // 动画组
        let group = CAAnimationGroup()
        group.duration = 0.9
        group.timingFunction = CAMediaTimingFunction(name: .easeOut)
        group.animations = [rotationAnim, moveAnim]
        group.fillMode = .forwards
        group.isRemovedOnCompletion = false
        return group
    }
    
    private func v5bH1SlyYCbABaky() -> CAAnimationGroup {
        // 缩放动画
        let scaleAnim = CABasicAnimation(keyPath: "transform")
        scaleAnim.toValue = NSValue(caTransform3D: CATransform3DMakeScale(1, 0, 1))
        
        // 下移动画
        let downAnim = CABasicAnimation(keyPath: "position.y")
        downAnim.toValue = progressLayer.position.y + self.s4r95rIqDiUNJQYY / 2
        
        // 动画组
        let group = CAAnimationGroup()
        group.fillMode = .forwards
        group.isRemovedOnCompletion = false
        group.animations = [scaleAnim, downAnim]
        return group
    }
    
    private func j5foJnq7d5H6ddLX() -> CAAnimationGroup {
        // 缩放动画
        let scaleAnim = CABasicAnimation(keyPath: "bounds.size")
        scaleAnim.toValue = NSValue(cgSize: CGSize(width: 1, height: bounds.width * progress))
        
        // 下移动画
        let downAnim = CABasicAnimation(keyPath: "position.y")
        downAnim.toValue = (bounds.width * progress) / 2 + 3
        downAnim.timingFunction = CAMediaTimingFunction(name: .easeIn)
        
        // 动画组
        let group = CAAnimationGroup()
        group.fillMode = .forwards
        group.isRemovedOnCompletion = false
        group.animations = [scaleAnim, downAnim]
        return group
    }
    
    private func rzCSMmrGMQ2fK2Bu() -> CAAnimationGroup {
        // 移动动画
        let moveAnim = CABasicAnimation(keyPath: "position.y")
        moveAnim.toValue = 200
        
        // 透明度动画
        let opacityAnim = CABasicAnimation(keyPath: "opacity")
        opacityAnim.toValue = 0
        
        // 动画组
        let group = CAAnimationGroup()
        group.animations = [moveAnim, opacityAnim]
        group.fillMode = .forwards
        group.isRemovedOnCompletion = false
        return group
    }
    
    // MARK: - CAAnimationDelegate
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if anim == self.YwDMX5reuL8EOlPi.layer.animation(forKey: self.ZBvVjUVz8p7Gv9Jy) {
            if flag {
                VSlnkd8KRp2HhFsy()
            }
        }
        
        if anim == self.YwDMX5reuL8EOlPi.layer.animation(forKey: self.MUBVr9vIKhBFT9am) {
            if flag {
                self.W2ibSoTH4X899TM3?.add(to: .current, forMode: .default)
                self.KY8FqIoEWu8BspOB = false
                self.kwMDFSOrxdZjDAWK = true
                readyBlock?(true)
            }
        }
    }
    
    // MARK: - 路径创建方法
    private func Stl4QlFQ7v5yoQ33() -> UIBezierPath {
        let path = UIBezierPath()
        let startPoint = self.YwDMX5reuL8EOlPi.layer.position
        let topPoint = CGPoint(x: startPoint.x, y: startPoint.y - 40)
        let horizentalPoint = CGPoint(x: startPoint.x, y: startPoint.y - 7.5)
        let rightPoint = CGPoint(x: startPoint.x + 20, y: horizentalPoint.y)
        let leftPoint = CGPoint(x: 0, y: horizentalPoint.y)
        
        path.move(to: startPoint)
        path.addLine(to: topPoint)
        path.addLine(to: horizentalPoint)
        path.addLine(to: rightPoint)
        path.addLine(to: leftPoint)
        
        return path
    }
    
    private func lagrRo1SCer3ifmP(with progress: CGFloat) -> UIBezierPath {
        let path = UIBezierPath()
        let startPoint = CGPoint(x: 0, y: bounds.height / 2)
        let endPoint = CGPoint(x: bounds.width * progress, y: startPoint.y)
        
        path.move(to: startPoint)
        path.addLine(to: endPoint)
        path.close()
        
        return path
    }
    
    
}
